package org.darcy.service.impl;

import org.darcy.dao.BizFileMapper;
import org.darcy.entity.BizFile;
import org.darcy.framework.blog.business.enums.FileUploadType;
import org.darcy.framework.blog.file.FileUploader;
import org.darcy.framework.blog.file.exception.GlobalFileException;
import org.darcy.framework.blog.plugin.file.GlobalFileUploader;
import org.darcy.framework.generic.GenericServiceImpl;
import org.darcy.service.BizFileService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

@Service
public class BizFileServiceImpl extends GenericServiceImpl<BizFile> implements BizFileService {

	@Autowired
	private BizFileMapper shopFileMapper;

	@Override
	public BizFile selectFileByPathAndUploadType(String filePath, String uploadType) {
		if (StringUtils.isEmpty(filePath)) {
			return null;
		}
		QueryWrapper<BizFile> q = new QueryWrapper<BizFile>();
		q.eq("file_path", filePath);
		if (StringUtils.isEmpty(uploadType)) {
			q.eq("upload_type", uploadType);
		}
		BizFile data = shopFileMapper.selectOne(q);
		return data;
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void remove(Long[] ids) {
		for (Long id : ids) {
			BizFile oldFile = this.getById(id);
			shopFileMapper.deleteById(oldFile);
			try {
				FileUploader uploader = new GlobalFileUploader();
				uploader.delete(oldFile.getFilePath(), oldFile.getUploadType());
			} catch (Exception ignored) {
			}
		}
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public int upload(MultipartFile[] file) {
		if (null == file || file.length == 0) {
			throw new GlobalFileException("请至少选择一张图片！");
		}
		for (MultipartFile multipartFile : file) {
			FileUploader uploader = new GlobalFileUploader();
			uploader.upload(multipartFile, FileUploadType.COMMON.getPath(), true);
		}
		return file.length;
	}

}
